package Test;

import com.sun.org.apache.xerces.internal.impl.XMLNamespaceBinder;

public class Test03 {
    /**
     * 链表的回文
     * 当head为null 时 , 返回false ,如果head.next 为空时 , 返回true
     * 1.先找到中间节点 , 快慢指针 , fast走两步 ,slow走一步
     * 2.将链表进行反转
     * 当cur不为空时
     * 定义cur 为slow.next , curNext 为cur.next .将cur.next给slow,slow往后走slow=cur,cur也往后走cur=curNext
     * 3.slow从后往前 ,head从前往后 当slow.val=head.val 则有回文数
     * 循环当slow!=head时(没有相遇), 如果head.val!=slow.val 返回false.
     * 偶数: 如果head.next==slow 则返回true
     * 奇数: 然后slow往前 slow=slow.next .head往后 head=head.next
     * 返回true
     */
    public boolean chkPalindrome(MySingleList.ListNode head) {
        if (head == null) {
            return false;
        }
        if (head.next == null) {
            return true;
        }
        MySingleList.ListNode fast = head;
        MySingleList.ListNode slow = head;
        //1. 找中间节点
        while (fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;
        }
        //2.反转
        MySingleList.ListNode cur = slow.next;
        while (cur != null) {
            MySingleList.ListNode curNext = cur.next;
            cur.next = slow;
            slow = cur;
            cur = curNext;
        }
        //3.从后往前走 , 从前往后走
        while (head != slow) {
            if (head.val != slow.val) {
                return false;
            }
            //偶数判断
            if (head.next == slow) {
                return true;
            }

            slow = slow.next;
            head = head.next;
        }
        return true;
    }

    public static void main(String[] args) {

    }

}
